<template>
  <div class="box-main1">
    <div class="box-header2">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/admin/index' }">控制台</el-breadcrumb-item>
        <el-breadcrumb-item>学生信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <slot :data="data"></slot>
    <div class="box-main2">
      <div class="box-search2">

        <div class="box-input2" style="width: 180px">
          <el-input  @keydown.enter.native="clkBtnSearch" @clear="clkBtnSearch" clearable
                     size="mini" v-model="searchInfo.searchKey" placeholder="学生名"></el-input>
        </div>
        <div class="box-input2">
          <el-button size="mini" type="primary" icon="el-icon-search" @click="clkBtnSearch">搜索</el-button>
          <el-button size="mini" type="warning" icon="el-icon-plus" @click="clkBtnAdd">新增</el-button>
        </div>

      </div>

      <div class="box-content2">
        <div class="box-table2">
          <el-table class="tbl1" :data="studentPage.list" :stripe="true" size="small">

            <el-table-column type="index" :index="(studentPage.pageNum-1)* studentPage.pageSize + 1" label="序号" width="55"></el-table-column>
            <el-table-column label="学号" width="100">
              <template slot-scope="scope">
                <span >{{scope.row.student_code}}</span>
              </template>
            </el-table-column>
            <el-table-column label="姓名" width="100">
              <template slot-scope="scope">
                <span >{{scope.row.student_realname}}</span>
              </template>
            </el-table-column>
            <el-table-column label="性别" width="60">
              <template slot-scope="scope">
                <span >{{scope.row.student_sex|filterSex}}</span>
              </template>
            </el-table-column>
            <el-table-column label="年龄" width="60">
              <template slot-scope="scope">
                <span >{{scope.row.student_age}}</span>
              </template>
            </el-table-column>
<!--            <el-table-column label="所属组" width="100">-->
<!--              <template slot-scope="scope">-->
<!--                <span >{{scope.row.studentGroupName}}</span>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="顺序号" width="60">
              <template slot-scope="scope">
                <span>{{scope.row.order_numb}}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建人" width="100">
              <template slot-scope="scope">
                <span>{{scope.row.createUserRealname}}</span>
              </template>
            </el-table-column>

            <el-table-column  label="操作" width="120">
              <template slot-scope="scope">
                 <span>
                   <el-button type="primary" size="mini" @click="clkBtnEdit(scope.row )">编辑</el-button>
                   <el-button type="warning" size="mini" @click="clkBtnDelete(scope.row )">删除</el-button>
                 </span>
              </template>
            </el-table-column>

          </el-table>
        </div>
        <div class="box-page2">
          <el-pagination layout="prev, pager, next" :total="studentPage.total"
                         :current-page="studentPage.pageNum" :page-size="studentPage.pageSize" @current-change="chgCurrPage">
          </el-pagination>
        </div>
      </div>
    </div>


    <el-dialog title="新增/编辑学生信息" class="dialog1"
               :show-close="false" :close-on-click-modal="false"
               :visible.sync="showSaveteStudentDialog">
      <div>
        <div class="box-content2">
          <div class="box-table2" style="width:420px">
            <el-form size="mini" ref="student" :model="student" label-width="120px">
              <el-form-item label="学生学号">
                <el-input v-model="student.student_code"></el-input>
              </el-form-item>
              <el-form-item label="学生真实姓名">
                <el-input v-model="student.student_realname"></el-input>
              </el-form-item>
              <el-form-item label="学生性别" >
                <el-radio-group v-model="student.student_sex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="所属学生组">
                <el-select v-model="student.student_group_id" placeholder="请选择学生组">
                  <el-option
                    v-for="item in studentGroupList"
                    :key="item.noid"
                    :label="item.student_group_name"
                    :value="item.noid">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="绑定登录账号">
                <el-input v-model="student.bind_usercode">
                  <el-button slot="append" @click="clkExamUsercode">验证</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="学生年龄">
                <el-input type="number" v-model="student.student_age"></el-input>
              </el-form-item>
              <el-form-item label="顺序号">
                <el-input type="number" v-model="student.order_numb"></el-input>
              </el-form-item>
            </el-form>
          </div>

        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="clkBtnSave">确 定</el-button>
        <el-button size="mini" @click="showSaveteStudentDialog = false">取 消</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
  import request from '@/common/utils/request';

  export default {
    computed: {
      loginUserInfo() {
        return this.$store.state.loginUserInfo;
      },

    },
    data() {
      return {
        searchInfo: {searchKey: null},
        studentPage: {pageNum:1 ,pageSize:12, list:[] },

        pageLoading: false,

        showSaveteStudentDialog: false,

        data: "",

        student: {},
        studentGroupList: [],
        radio: "1",
      };
    },
    mounted() {
      this._initData();
    },
    watch: {
      $route: {
        handler: function (to, from) {
          if (to.path == '/admin/student_list') {
            this._initData();
          }
        }, immediate: true
      }
      //   // lambda 语法
      //   handler: (newVal,oldVal) =>{
      //     if(newVal.path == '/student_group/list'){
      //
      //     }
      //   }, immediate: true
    },
    methods: {
      _initData() {
        this.loadStudentGroupList();
        this.getList();
      },

      clkBtnSearch() {
        this.getList();
      },
      loadStudentGroupList(){
        let url1 = this.settings.apiUrl + '/student_group/list';
        let d1 = {};

        request.post(url1, d1).then((d1r) => {
          if (d1r.code === 0) {
            this.studentGroupList = d1r.data;
          }
        })
      },
      getList() {
        let url1 = this.settings.apiUrl + '/student/page';
        let d1 = {};
        d1.pageNum = this.studentPage.pageNum;
        d1.pageSize = this.studentPage.pageSize;

        d1.searchKey = this.searchInfo.searchKey;

        request.post(url1, d1).then((d1r) => {
          this.pageLoading = false;
          if (d1r.code === 0) {
            this.studentPage = d1r.data;

          } else {

            this.$alert('获取用户信息失败：' + d1r.msg, '提示', {
              type: 'warning'
            });

          }
        }).catch(err => {
          this.pageLoading = false;
        });
      },
      // 点击新增用户的按钮
      clkBtnAdd() {
        this.student = {};
        this.showSaveteStudentDialog = true;
      },
      clkBtnEdit(row) {
        this.student = JSON.parse(JSON.stringify(row));
        this.showSaveteStudentDialog = true;

      },

      clkBtnDelete(row) {

        this.$confirm('您确信要删除该记录吗', "提示").then(() => {

          let url1 = this.settings.apiUrl + '/student/delete';
          let d1 = {noid: row.noid};
          request.post(url1, d1).then((d1r) => {
            if (d1r.code === 0) {
              // 记录密码
              this.getList();
              this.$message('您删除成功了。');
            } else {
              this.$alert('新增学生组失败：' + d1r.msg, '提示', {
                type: 'warning'
              });
            }
          }).catch(err => {
            this.loading = false;
            console.log(err);
          });

        })


      },

      clkBtnSave() {
        // 1 首先做验证
        let url1 = this.settings.apiUrl + '/student/save';
        let d1 = this.student;
        d1.create_user_id = this.loginUserInfo.noid;

        request.post(url1, d1).then((d1r) => {
          if (d1r.code === 0) {
            // 记录密码
            this.getList();
            this.showSaveteStudentDialog = false;
          } else {
            this.$alert('新增学生失败：' + d1r.msg, '提示', {
              type: 'warning'
            });
          }
        }).catch(err => {
          this.loading = false;
          console.log(err);
        });


      },
      chgCurrPage(val){
        this.studentPage.pageNum = val;
        this.getPage();
      },
      getPage(){
        this.getList();
      },
      clkExamUsercode(){
        // ??? 要做的是 userInfo里面是否存在 usercode，
        //  反正肯定应该是 userInfo 模块的， 是什么方法 ？？？
        let url1 = this.settings.apiUrl + '/user_info/validUserCode';
        // d1 必须是 js 对象 ，如何实现 ???
        // let str = this.student.bind_usercode;
        let d1 = {'usercode': this.student.bind_usercode};
        // 1 提交服务端进行 usercode验证，验证是否存在该usercode

        request.post(url1, d1).then(d1r => {
          if (d1r.code == 0) {
            this.$message("可以使用~");
          } else {
            this.$confirm('该账号不存在，是否创建?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'success'
            }).then(() => {

              // 确定要创建的时候， 再次使用request 执行快速创建
              let url2 = this.settings.apiUrl + "/user_info/add";
              let d2 = {'usercode': this.student.bind_usercode, 'userpwd' : '111111',
                'realname': this.student.student_realname, 'noid': this.student.noid,
                'permissions':[]};

              request.post(url2, d2).then(d2r => {
                if (d2r.code == 0) {
                  this.$message("创建成功~");

                }


              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消创建'
              });
            });
          }
        })
        // 1.1 如果存在则提示可以使用


        // 1.2 如果不存在，则提示是否快速创建账号
        // 快速创建的账号、用户名都是该usercode，登录密码为 111111，没有任何权限


      },
      clkCreateUser(){
        console.log('alert')
      }

    },
    filters:{
      filterSex(srcVal){
        if(srcVal==1){
          return '男';
        }
        if(srcVal==2){
          return '女';
        }
        return '未知';
      }
    }

  };
</script>

<style lang="scss" scoped="scoped">

  .box-main2 {
    height: 100%;
    background-repeat: no-repeat;
    background-size: cover;
  }

  .box-header2{
    height: 30px;
    background-color: #eceeef;
    padding-left:20px;
    padding-top:8px;

  }

  .box-search2{
    display: flex;
  }
  .box-page2{
    display: flex;
    justify-content: flex-end;
  }

  .box-search2{
    padding-bottom: 10px;
    .box-input2{
      padding-right:10px;
    }
  }



</style>
